package com.deer.wms.system.manage.service.impl;

import com.deer.wms.intercept.entity.SecurityUser;
import com.deer.wms.intercept.entity.UserLogin;
import com.deer.wms.project.root.core.result.CommonCode;
import com.deer.wms.project.root.exception.ServiceException;
import com.deer.wms.system.manage.model.user.UserInfo;
import com.deer.wms.system.manage.service.PermissionService;
import com.deer.wms.system.manage.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author : wei
 * @since : 2021-07-30 10:41:14
 **/
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private PermissionService permissionService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询数据
        UserInfo userInfo = userInfoService.findUserInfoByAccount(username);
        if (userInfo == null) {
            throw new ServiceException(CommonCode.SERVICE_ERROR, "帐号未注册或未激活");
        }
        UserLogin userLogin = new UserLogin();
        userLogin.setAccount(username);
        userLogin.setPassword(userInfo.getPassword() + "," + userInfo.getAccount() + "," + userInfo.getSalt());

        //根据用户查询用户权限列表
        List<String> permissionValueList = permissionService.findPermissionCodeByUserId(userInfo.getUserId());

        SecurityUser securityUser = new SecurityUser();
        securityUser.setCurrentUserInfo(userLogin);
        securityUser.setPermissionValueList(permissionValueList);
        return securityUser;
    }
}
